package com.ruoyi.common.utils.wechat;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Component
public class AccessToken {

    @Autowired
    RedisCache redisCache;
    private static RedisCache getRedisCach;

    // 通过注入方式将数据注入到实体中
    @PostConstruct
    public void init() {
        getRedisCach = redisCache;
    }

    public static String getAccessToken(String appId, String appSecret) {
        if (getRedisCach.hasKey(appId)) {
            return getRedisCach.getCacheObject(appId);
        } else {
            JSONObject accessToken = RequestUtils.getAccessToken(appId, appSecret);
            String access_token = accessToken.getString("access_token");
            int expires_in = accessToken.getInteger("expires_in");
            getRedisCach.setCacheObject(appId, access_token, expires_in, TimeUnit.SECONDS);
            return access_token;
        }

    }
}
